# -*- coding: utf-8 -*-
import websockets
import asyncio
import select
import traceback
import ujson
import aiohttp
import traceback
from random import uniform
from datetime import datetime


# 引入自己写好的消息解析模块
from MessageParse import MessageParse
# WF机器人
import WFbot

# 使用反向websockets的过程中出现了长时间没有消息后无法再次收到消息的问题，不知道为什么，因此改用正向，我去连接服务器

websocket_list = set()
debug = 1
rate_limit_time = datetime.now()  # 控制发送时间


# 以下是wf的模块
async def updateWfData():
    pass


# 以下是机器人本身的模块
# 按长度分隔，如果text大于等于80个字符，则需要将字符串进行分割
def split_text(text, maxlen=80):
    def cut(obj, sub_len):  # 这个函数也有问题
        str_list = [obj[i:i+sec] for i in range(0, len(obj), sec)]
        return str_list
    t = list()
    if len(text) <= 80:
        t.append(text)
        return t
    else:
        num = 0
        tt = ""
        a = text.split("\n")
        for i in a:
            t_len = len(i)
            if num + t_len + 1 <= maxlen:  # 如果tt加上i后的长度小于80的话，就将i放入t
                tt += i + '\n'
                num += t_len
            else:  # 否则将i放入另一个tt中
                t.append(tt)
                tt = ""
                num = 0
                if t_len > maxlen:
                    for j in cut(i, maxlen):  # 将i按80进行分割
                        t.append(j)
                else:
                    tt += i + '\n'
                    num += t_len
        if debug:
            print("split_text返回: ", t)
        return t


async def sendGroupMsg(groupid, text="开发中"):
    t = {
        "group_id": groupid,
        "message": text,
        'auto_escape': False
    }

    async with aiohttp.request("POST", "http://127.0.0.1:5700/send_group_msg", data=t) as f:
        print("发送群消息，返回：", await f.text())


async def sendPrivateMsg(userid, text=None, group_id=None):
    if group_id is None:
        t = {
            "user_id": userid,
            "message": text,
            'auto_escape': False
        }
    else:
        t = {
            "user_id": userid,
            "group_id": group_id,
            "message": text,
            'auto_escape': False
        }

    async with aiohttp.request("POST", "http://127.0.0.1:5700/send_private_msg", data=t) as f:
        print("发送私聊消息，返回：", await f.text())


# 将要发送到群里的消息转发为私聊消息
async def Group2Privete(group_id, user_id, p_text, g_text="已私聊发送~\n若无法收到请加机器人好友"):  # g_text是从群里发起私聊的时候，往群里发的提示消息
    try:
        # g_t = {
        #     "group_id": group_id,
        #     "message": g_text,
        #     'auto_escape': False
        # }
        await sendGroupMsg(group_id, g_text)
        # async with aiohttp.request("POST", "http://127.0.0.1:5700/send_group_msg", data=g_t) as f:
        #     print("Group2Privete()中发送群消息，返回：", await f.text())
        # p_t = {
        #     "user_id": user_id,
        #     "group_id": group_id,
        #     "message": p_text,
        #     'auto_escape': False
        # }
        await sendPrivateMsg(user_id, p_text, group_id)
        # async with aiohttp.request("POST", "http://127.0.0.1:5700/send_private_msg", data=p_t) as f:
        #     print("Group2Privete()中发送私聊消息，返回：", await f.text())
    except:
        traceback.print_exc()


async def parseMsg2(text):
    global rate_limit_time
    if debug:
        print("收到消息, ", text)
    # return
    # 如果有消息
    if text:
        resId = 0
        json = ujson.loads(text)
        if debug:
            print("json.loads:")
            print(json)
        # 处理未过滤掉的一些消息，比如心跳等
        if "message_type" not in json.keys():
            pass
        else:
            # 解析消息，获取对象
            message = MessageParse(json["raw_message"])
            if debug:
                print("message对象是：\n", message)
            # 如果是群聊消息，获取群号
            if json["message_type"] == "group":
                resId = json["group_id"]  # 群号
                msg = message.msg  # 命令
                if debug:
                    print("in bot.py, 得到的msg = ", msg)
                # 如果是WF新手群中调用bot
                if resId == 414922009 or resId == 739060938:
                    m = parseWfbot(msg)
                    if debug:
                        print("在bot.py中，使用wfbot时，返回: ", m)
                    if m:
                        if m[1] == "g":  # 发送到群内
                            now = datetime.now()
                            if (now - rate_limit_time).seconds > 10:
                                rate_limit_time = now
                                await sendGroupMsg(resId, m[0])
                        else:
                            await Group2Privete(resId, json["sender"]["user_id"], m[0])
                    else:  # 暂时是翻译和留言模块专用
                        msg_data = message.command_data
                        msg = message.command_name
                        t = parseWfbot_no_private(msg, msg_data, json["sender"]["user_id"])
                        if t:
                            await sendGroupMsg(resId, t)
                if msg == '测试':
                    await sendGroupMsg(resId, WFbot.readCambionDriftStatus())
                elif msg == '测试2':
                    ttt = WFbot.ceshi()
                    await sendGroupMsg(resId, ttt)
                elif message.command_name == '测试3':
                    command = message.command_data[0]
                    if debug:
                        print("测试3发出的参数是：", command)
                    await sendGroupMsg(resId, parseWfbot(command))
                else:
                    pass

            # 私聊获取私聊id
            elif json["message_type"] == "private":
                resId = json["user_id"]
                msg = message.msg
                if message.command_name == "手动调用":
                    c = message.command_data[0]  # 具体需要调用的函数
                    await doWfbot(c)
                print("私聊，传入parseWfbot()的参数message.msg = ", msg)
                m = parseWfbot(msg)
                print("在bot.py中，私聊使用wfbot时，返回: ", m)
                if m:
                    await sendPrivateMsg(resId, m)
                else:  # 暂时是翻译和留言模块专用
                    msg = message.command_name
                    msg_data = message.command_data
                    t = parseWfbot_no_private(msg, msg_data, resId)
                    if t:
                        await sendPrivateMsg(resId, t)
            else:
                pass


def parseWfbot(text, data=None):
    print("in bot.parseWfbot(), text=", text)
    if text in ["魔胎之境", "火卫二"]:
        return (WFbot.readCambionDriftStatus(), "g")
    elif text in ["希图斯", "地球平原", "平原时间", "地球"]:
        return (WFbot.readCetusCycle(), "g")
    elif text in ["金星平原", "奥布山谷", "金星"]:
        return (WFbot.readVallisCycle(), "g")
    elif text in ["突击", "每日突击"]:
        return (WFbot.readSotie(), "p")
    elif text == "裂隙":
        return (WFbot.readFissures(), "p")
    elif text == "仲裁":
        return (WFbot.readArbitration(), "p")
    elif text == "入侵":
        return (WFbot.readInvasions(), "p")
    elif text in ["虚空商人", "奸商"]:
        return (WFbot.readVoidTrader(), "p")
    elif text == "帮助":
        return (WFbot.getHelp(), "p")
    else:
        return None

# senderid是发送者的id，为了防止机器人把自己发出的翻译再次翻译
def parseWfbot_no_private(text, data=None, senderid=None):
    if text == "翻译":
        if senderid == 2230722008:
            return None
        try:
            tt = ' '.join(data)
            t = WFbot.translate(tt)
            if t == None:
                return tt + " " + tt
            else:
                return tt + " " + t
        except:
            return None
    elif text == "留言":
        try:
            tt = ' '.join(data)
            return WFbot.comment(tt)
        except:
            return None
    else:
        return None

async def doWfbot(text):
    print("in bot.parseWfbot(), text=", text)
    if text in ["魔胎之境", "火卫二"]:
        await WFbot.updateCambionDriftStatus()
    elif text in ["希图斯", "地球平原"]:
        await WFbot.updateCetusCycle()
    elif text in ["金星平原", "奥布山谷"]:
        await WFbot.updateVallisCycle()
    elif text in ["突击", "每日突击"]:
        await WFbot.updateSotie()
    elif text == "裂隙":
        await WFbot.updateFissures()
    elif text == "仲裁":
        await WFbot.updateArbitration()
    elif text == "入侵":
        await WFbot.updateInvasions()
    elif text in ["虚空商人", "奸商"]:
        await WFbot.updateVoidTrader()
    else:
        return None

# 服务器端主逻辑
# websocket和path是该函数被回调时自动传过来的，不需要自己传
async def mainLogic():
    async with websockets.connect("ws://127.0.0.1:6700") as websocket:
        while True:
           await parseMsg2(await websocket.recv())

# 加载wf字典，加载失败就退出
# 为什么换一下顺序，先执行dictLoad()、update就无法运行呢？
task_list = [
    # WFbot.updateCambionDriftStatus(),
    # WFbot.updateCetusCycle(),
    WFbot.initUpdate(),
    WFbot.dictLoad()
    
]
done, pending = asyncio.run( asyncio.wait(task_list) )
print(done)

loop=asyncio.new_event_loop()
loop.run_until_complete(mainLogic())
loop.run_forever()
